package com.student.xujiang.mysmalluse.retrofitandrxjava;

import android.util.Log;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

/**
 * Created by xujiang on 2017/3/21.
 */
//okhttp源码解析
//http://blog.csdn.net/new_abc/article/details/53006462

public class ServiceGenerator {

    public static final String TAG = ServiceGenerator.class.getSimpleName();

    public static final String API_BASE_URL = "https://api.github.com";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(API_BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create());
            //.addCallAdapterFactory(RxJavaCallAdapterFactory.create());


    public static <S> S CreateService(Class<S> serviceClass){
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }

    public static void getgithuballapi(){
        /**
         * 首先利用前面的ServiceGenerator来创建Service,
         * 然后调用接口中定义的getAllEndpoints()方法, 此处传入了空字符串,
         * 因为我请求的就是base url.
         *
         * */
        GitHubService gitHubService = ServiceGenerator.CreateService(GitHubService.class);
        Call<Endpoints> endpointsCall = gitHubService.getAllEndPointss("");
        /**
         * 同步和异步
         这里注意用Retrofit请求的返回值是Call<T> (后面我们还会介绍用RxJava的情形), 泛型T是model类型, 它有两个方法:
         execute()是同步方法, 返回Response<T>;
         enqueue()是异步方法, 在上面的例子中用的就是这个, 在回调onResponse()中返回了Response<T>
         *
         * */
        endpointsCall.enqueue(new Callback<Endpoints>() {


            @Override
            public void onResponse(Call<Endpoints> call, Response<Endpoints> response) {
                Endpoints endpoints = response.body();
                String repositoryUrl = endpoints.getRepositoryUrl();
                Log.i(TAG,repositoryUrl);

            }

            @Override
            public void onFailure(Call<Endpoints> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }



}
